package com.txby.platformApi.component.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.jck.mybatis.util.IdWorker;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.pf.common.annotation.SysLog;
import com.txby.pf.common.utils.Constant;
import com.txby.pf.common.utils.PageUtils;
import com.txby.pf.common.utils.Query;
import com.txby.pf.common.utils.R;
import com.txby.pf.common.validator.ValidatorUtils;
import com.txby.pf.common.validator.group.AddGroup;
import com.txby.pf.modules.oss.cloud.OSSFactory;
import com.txby.pf.modules.oss.entity.SysOssEntity;
import com.txby.platformCore.entity.Sysversion;

/**
 * APP版本控制
 */
@RestController
@RequestMapping("/pro/sysversion")
public class SysversionController  extends CommonController {
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("pro:sysversion:list")
	public R list(@RequestParam Map<String, Object> params){
//		数据隔离
		/*String join="";*/
		String sql="SELECT * FROM  "+this.mBaseDao.tableName(Sysversion.class);
		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
		/*	 join=getJoinSqlBracket();
			 sql+=" and deptId in "+getJoinSqlBracket();*/
		}
		String appName=params.get("appName")==null?"":params.get("appName").toString();
		if(!ChkUtil.isEmptyAllObject(appName)){
			if (appName.contains("%") || appName.contains("_")) {
				appName = appName.trim().replace("%", "\\%").replace("_", "\\_");
				appName = "%" + appName + "%";
				sql += " and appName like #{pojo.appName} escape '\\'";
				params.put("appName", "%" + appName.trim() + "%");
			} else {
				appName = "%" + appName.trim() + "%";
				sql += " and appName like #{pojo.appName} ";
				params.put("appName", "%" + appName.trim() + "%");
			}
		}
		sql += Query.getLastSortSql(params, " order by updateTime ");
		//查询列表数据
		PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		PageUtils pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	
 
	/**
	 * 查询
	 */
	@RequestMapping("/query")
	public R query(@RequestBody Integer flag){
		String sql="SELECT versionCode FROM `t_txby_sys_Version`  WHERE flag="+flag+" ORDER BY versionCode desc LIMIT 1";
		Object query=this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		
		return R.ok().put("query", query==null? -1:((Map)query).get("versionCode"));
		
	}
	
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("pro:sysversion:info")
	public R info(@PathVariable("id") Long id){
		String sql="SELECT * FROM  "+this.mBaseDao.tableName(Sysversion.class)+"  WHERE id_="+id+"" ;
		Map sysversion =  (Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return R.ok().put("sysversion", sysversion);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("pro:sysversion:save")
	public R save(@RequestBody Sysversion sysversion){
		try{
		ValidatorUtils.validateEntity(sysversion);
		String sql="select * from "+this.mBaseDao.tableName(Sysversion.class)+" where versionCode="+sysversion.getVersionCode()+" and flag=" 
				+sysversion.getFlag()+" ORDER BY versionCode DESC LIMIT 1";
		Sysversion old=(Sysversion) this.mBaseDao.findBySqlUniqueObject(sql, Sysversion.class, null);
		 if(old!=null){
			 return R.ok().error("标识号重复");
		 }
		 sysversion.setCreater(getUserId().toString());
		 sysversion.setUpdater(getUserId().toString());
			this.mBaseDao.saveObject(sysversion);
		}catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("pro:sysversion:update")
	public R update(@RequestBody  Sysversion sysversion){
		try{
		ValidatorUtils.validateEntity(sysversion);
		   String sql="select * from "+this.mBaseDao.tableName(Sysversion.class)+" where versionCode='"+sysversion.getVersionCode()+"' and flag=" 
					+sysversion.getFlag()+ " and id_!="+sysversion.getId_()+" ORDER BY versionCode DESC LIMIT 1";
		   Sysversion old=(Sysversion) this.mBaseDao.findBySqlUniqueObject(sql, Sysversion.class, null);
		 if(old!=null){
			 return R.ok().error("标识号重复");
		 }else{
			 old=(Sysversion) this.mBaseDao.findBySqlUniqueObject("select * from "+this.mBaseDao.tableName(Sysversion.class)+" where   id_="+sysversion.getId_(), Sysversion.class, null);
			 if(old!=null){
				 this.mBaseDao.updateObject(sysversion);
			 }
		 }
		}catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("pro:sysversion:delete")
	public R delete(@RequestBody Long[] ids){
		 for(Long id:ids){
		    	this.mBaseDao.executeSql(" delete from "+this.mBaseDao.tableName(Sysversion.class)+" where id_="+id+"", null);
		  }
			return R.ok();
	}
	
	
	/**
	 * 上传apk文件
	 * @throws IOException 
	 */
	@SysLog("上传apk文件")
	@RequestMapping("/saveUpload")
	public R saveUpload(@RequestParam("apkFile") MultipartFile apkFile) throws IOException{
	      String url=getOssUploadUrl(apkFile, apkFile.getOriginalFilename());
	      if(!ChkUtil.isEmpty(url)){
	    	  return R.ok().put("url", url);
	      }else{
	    	  return R.error("上传失败");
	      }
	}
	public String getOssUploadUrl(MultipartFile apkFile, String fileName) throws IOException {
		InputStream in =apkFile.getInputStream();
		String path = "/apks/" + IdWorker.get32UUID() + fileName;
		// 上传文件
		String url = OSSFactory.build().upload(in, path);
		// 保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		this.sysOssService.save(ossEntity);
		System.out.println(url);
		return url;
	}
}
